package com.hanson.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.Const;
import com.hanson.common.bean.WeiXinConfig;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.service.RedisService;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.ApplyInfoBean;
import com.hanson.entity.UserBean;
import com.hanson.mapper.ApplyInfoBeanMapper;
import com.hanson.mapper.UserBeanMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ApplyInfoService {
    @Autowired
    private ApplyInfoBeanMapper applyInfoBeanMapper;
    @Autowired
    private UserBeanMapper userBeanMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private WeiXinConfig weiXinConfig;
    @Value("${oss.local}")
    private String isLocal;

    @Transactional(rollbackFor = Exception.class)
    public String addApplyInfo(String openId, ApplyInfoBean applyInfoBean) {
        if (applyInfoBean.getType() != 1 && applyInfoBean.getType() != 2 && applyInfoBean.getType() != 3) {
            throw new BusinessException("申请类型不正确！");
        }
        List<ApplyInfoBean> applyInfoBeanList = applyInfoBeanMapper.selectByOpenIdAndType(openId, applyInfoBean.getType());
        String paySeq = null;
        int orderType = 0;
        if (CollectionUtils.isNotEmpty(applyInfoBeanList)) {
            applyInfoBeanList.stream().forEach(c -> {
                applyInfoBeanMapper.deleteByPrimaryKey(c.getId());
            });
        }

        if (applyInfoBean.getType() == 1) {
            orderType = 2;
        } else if (applyInfoBean.getType() == 2) {
            orderType = 3;
        } else if (applyInfoBean.getType() == 3) {
            orderType = 4;
        }
        paySeq = BusinessUtil.getOrderSeq(orderType);
        applyInfoBean.setOpenId(openId);
        applyInfoBean.setStatus(applyInfoBean.getType() == 3 ? 0 : -1);
        applyInfoBean.setCreateDate(new Date());
        applyInfoBean.setIsPay(0);
        applyInfoBean.setPaySeq(paySeq);
        if (StringUtils.isNotEmpty(applyInfoBean.getYyzzImage())) {
            applyInfoBean.setYyzzImage(applyInfoBean.getYyzzImage().replaceAll("&amp;", "&"));
        }
        if (StringUtils.isNotEmpty(applyInfoBean.getSfzhImage1())) {
            applyInfoBean.setSfzhImage1(applyInfoBean.getSfzhImage1().replaceAll("&amp;", "&"));
        }
        if (StringUtils.isNotEmpty(applyInfoBean.getSfzhImage2())) {
            applyInfoBean.setSfzhImage2(applyInfoBean.getSfzhImage2().replaceAll("&amp;", "&"));
        }
        applyInfoBeanMapper.insert(applyInfoBean);
        return paySeq;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateApplyInfo(ApplyInfoBean applyInfoBean) {
        ApplyInfoBean returnBean = applyInfoBeanMapper.selectByPrimaryKey(applyInfoBean.getId());
        if (returnBean != null) {
            returnBean.setUpdateDate(new Date());
            returnBean.setStatus(applyInfoBean.getStatus());
            returnBean.setRemark(applyInfoBean.getRemark());
            applyInfoBeanMapper.updateByPrimaryKey(returnBean);
            UserBean userBean = userBeanMapper.selectByOpenId(returnBean.getOpenId());
            if (null != userBean) {
                //VIP申请
                if (returnBean.getType() == 1 && returnBean.getStatus() == 1) {
                    if (userBean.getIsVip() == 0) {
                        userBean.setIsVip(1);
                        userBeanMapper.updateByPrimaryKeySelective(userBean);
                        redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));
                    }
                }
                //VIP申请不通过
                if (returnBean.getType() == 1 && returnBean.getStatus() == 2) {
                    if (userBean.getIsVip() == 1) {
                        userBean.setIsVip(0);
                        userBeanMapper.updateByPrimaryKeySelective(userBean);
                        redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));
                    }
                }
                //合伙人申请
                if (returnBean.getType() == 2 && returnBean.getStatus() == 1) {
                    if (userBean.getIsSpread() == 0) {
                        String qrUrl = null;
                        try {
                            //开始生成二维码
                            qrUrl = BusinessUtil.generateQRCodeImage(isLocal,String.format("%sweb/userCenter?parentId=%s", weiXinConfig.getDomian(), returnBean.getOpenId()), 277, 275);
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error("【生成二维码到OSS失败】", e);
                        }
                        userBean.setSignDate(new Date());
                        userBean.setUserSign(qrUrl);
                        userBean.setIsSpread(1);
                        userBeanMapper.updateByPrimaryKeySelective(userBean);
                        redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));
                    }
                }
                //合伙人申请不通过
                if (returnBean.getType() == 2 && returnBean.getStatus() == 2) {
                    if (userBean.getIsSpread() == 1) {
                        userBean.setIsSpread(0);
                        userBeanMapper.updateByPrimaryKeySelective(userBean);
                        redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));
                    }
                }
                //掌柜申请
                if (returnBean.getType() == 3 && returnBean.getStatus() == 1) {
                    if (userBean.getUserType().equals("1")) {
                        userBean.setUserType("2");
                        userBean.setAccountName(String.valueOf(1000 + userBean.getId()));
                        userBean.setPassword("123456");
                        userBeanMapper.updateByPrimaryKeySelective(userBean);
                        redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));
                    }
                }
                //掌柜申请不通过
                if (returnBean.getType() == 3 && returnBean.getStatus() == 2) {
                    if (userBean.getUserType().equals("2")) {
                        userBean.setUserType("1");
                        userBean.setUserName("");
                        userBean.setPassword("");
                        userBeanMapper.updateByPrimaryKeySelective(userBean);
                        redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));
                    }
                }
            }
        }
    }

    public ApplyInfoBean detailApplyInfo(Integer id) {
        return applyInfoBeanMapper.selectByPrimaryKey(id);
    }

    public void deleteApplyInfo(Integer id) {
        applyInfoBeanMapper.deleteByPrimaryKey(id);
    }

    public Page<ApplyInfoBean> listApplyInfoBean(Page<ApplyInfoBean> page, ApplyInfoBean applyInfoBean) {
        List<ApplyInfoBean> list = applyInfoBeanMapper.listApplyInfoBean(page, applyInfoBean);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                c.setWebPayMoney(BusinessUtil.getWebAmount(c.getPayMoney()));
            });
        }
        return page.setRecords(list);
    }

    public List<ApplyInfoBean> selectByPaySeq(String paySeq) {
        return applyInfoBeanMapper.selectByPaySeq(paySeq);
    }

    public void updatePayStatus(int isPay, int payMoney, String paySeq) {
        applyInfoBeanMapper.updatePayStatusByPaySeq(isPay, payMoney, paySeq);
    }

    public List<ApplyInfoBean> selectByOpenIdAndType(String openId, Integer type) {
        return applyInfoBeanMapper.selectByOpenIdAndType(openId, type);
    }

    public void deleteByOpenIdAndType(String openId, Integer type) {
        applyInfoBeanMapper.deleteByOpenIdAndType(openId, type);
    }
}
